﻿var Mail = function () {
    var C = {
        Components: {
            // UE编辑器
            UEditor: null,
            btnNewBox: $("#btnNewBox"),
            btnInbox: $("#btnInbox"),
            btnSendBox: $("#btnSendBox"),
            btnDraftBox: $("#btnDraftBox"),
            btnTrashBox: $("#btnTrashBox"),
            mailContent: $("#mailContent"),
            LoadingPanel: $("#mailbox_loading"),
            mailCountLabel: $("#labelInboxCount, span.badge-mail"),
            currentButton: null
        },
        // 全局数据
        Data: {
            // 收件人信息
            Receiver: null,
            MailBox: null
        },
        // 初始化
        init: function () {
            toastr.options = {
                "closeButton": false,
                "debug": false,
                "positionClass": "toast-top-center",
                "onclick": null,
                "showDuration": "500",
                "hideDuration": "500",
                "timeOut": "2000",
                "extendedTimeOut": "1000",
                "showEasing": "swing",
                "hideEasing": "linear",
                "showMethod": "fadeIn",
                "hideMethod": "fadeOut"
            };

            var btns = [
                this.Components.btnNewBox,
                this.Components.btnInbox,
                this.Components.btnSendBox,
                this.Components.btnDraftBox,
                this.Components.btnTrashBox
            ];
            var mailContent = this.Components.mailContent;
            mailContent.LoadingPanel = $("#mailbox_loading");
            mailContent.Title = $("#mailbox_title");
            this.Components.currentButton = this.Components.btnInbox;

            for (var i in btns) {
                var T = btns[i];

                T.bind("click", function (e) {
                    var link = $(this);
                    var type = "";
                    var postData = new PostData();

                    e.preventDefault();

                    switch (this.id) {
                        case "btnNewBox":
                            type = "new";
                            break;
                        case "btnInbox":
                            type = "inbox";
                            break;
                        case "btnSendBox":
                            type = "send";
                            break;
                        case "btnDraftBox":
                            type = "draft";
                            break;
                        case "btnTrashBox":
                            type = "trash";
                            break;
                    }

                    postData.Add("action", link.attr("href"));
                    postData.Add("mailbox", type);

                    C.setHashParams(postData.GetData());
                });
            }

            mailContent.delegate("th.pagination-control > a:not(.disabled)", "click", function (e) {
                e.preventDefault();

                var params = C.getHashParams(location.hash);
                var newparms = null;
                var arr = this.href.match(/\?[^^]+/);

                if (arr) {
                    newparms = C.getHashParams("#" + Base64.encode(arr[0].substr(1)));
                }

                C.setHashParams($.extend(params, newparms));
            });

            this.initHashChange();
        },
        // 初始化编辑器
        initEditor: function () {
            if (C.Components.UEditor) {
                C.Components.UEditor.destroy();
            }

            var txtSendTo = $("#sendto");
            var txtSubject = $("#txtSubject");
            var hdfMID = $("#mid");
            var btnSend = $("#btnSend");
            var btnSaveDraft = $("#btnSaveDraft");
            var btnSend = $("#btnSend");
            var btnDelete = $("#btnCancelAndDelete");
            C.Components.UEditor = UE.getEditor("editor");

            if (C.Data.Receiver) {
                var receiver = [];
                for (var i in C.Data.Receiver) {
                    receiver.push(C.Data.Receiver[i].UID);
                }
                txtSendTo[0].defaultValue = receiver.join(",");
            }

            txtSendTo.select2({
                placeholder: "查找联系人",
                minimumInputLength: 2,
                ajax: {
                    url: "/C/GetContacts",
                    dataType: 'json',
                    type: "POST",
                    quietMillis: 200,
                    data: function (term, page) {
                        return {
                            q: term, // search term
                            count: 10,
                            ajax: true
                        };
                    },
                    results: function (data, page) {
                        if (data.Data) {
                            for (var i in data.Data) {
                                data.Data[i]["id"] = data.Data[i].UID;
                            }
                        }

                        return {
                            results: data.Data
                        };
                    },
                    cache: true
                },
                tags: [],
                initSelection: function (element, callback) {
                    // 若input没有value，则该部分不能被触发到
                    for (var i in C.Data.Receiver) {
                        C.Data.Receiver[i]["id"] = C.Data.Receiver[i]["UID"];
                    }
                    callback(C.Data.Receiver);
                },
                formatNoMatches: function (term) {
                    return "没有找到相关联系人";
                },
                formatSearching: function () {
                    return "正在查询……";
                },
                formatInputTooShort: function (term, minLength) {
                    return "还需要输入" + (minLength - term.length) + "个字符";
                },
                formatResult: function (rsp) {
                    var item = '<div class="clearfix">';
                    item += '<div class="pull-left"><img src="' + rsp.PicUrl + '" height="30"></div>';
                    item += '<div class="pull-left ml-20">' + rsp.FullName + ' (' + rsp.UID + ')</div>';
                    item += '</div>';

                    return item;
                },
                formatSelection: function (rsp) {
                    return rsp.FullName;
                },
                dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
                escapeMarkup: function (m) {
                    return m;
                } // we do not want to escape markup since we are displaying html in results
            });

            function setComponentsEnable(enabled) {
                if (enabled) {
                    txtSubject.removeAttr("disabled");
                    btnSaveDraft.removeAttr("disabled");
                    btnSend.removeAttr("disabled");
                    btnDelete.removeAttr("disabled");
                    txtSendTo.select2("enable", true);
                    C.Components.UEditor.setEnabled();
                } else {
                    txtSubject.attr("disabled", "disabled");
                    btnSaveDraft.attr("disabled", "disabled");
                    btnSend.attr("disabled", "disabled");
                    btnDelete.attr("disabled", "disabled");
                    txtSendTo.select2("enable", false);
                    C.Components.UEditor.setDisabled('fullscreen');
                }
            }

            // 绑定发送事件
            btnSend.bind("click", function () {
                var postData = [];
                var touid = txtSendTo.val().split(",");
                var subject = txtSubject.val();

                if (touid.length == 0) {
                    toastr["warning"]("请填写收件人信息", "发送邮件");
                    return false;
                }

                if (!subject.replace(/^\s+|\s+$/, "")) {
                    toastr["warning"]("请填写邮件主题", "发送邮件");
                    return false;
                }

                postData.push({ "name": "mid", "value": hdfMID.val() });
                postData.push({ "name": "subject", "value": subject });
                postData.push({ "name": "context", "value": C.Components.UEditor.getContent() });
                postData.push({ "name": "ajax", "value": true });

                for (var i in touid) {
                    postData.push({ "name": "touid", "value": touid[i] });
                }

                var btntext = btnSend.html();
                setComponentsEnable(false);
                btnSend.empty().append('<i class="fa fa-spinner fa-spin"></i> 正在发送');

                $.ajax({
                    url: "/Mail/Send",
                    type: "POST",
                    dataType: "json",
                    data: postData,
                    success: function (rsp) {
                        if (rsp.Result) {
                            toastr["success"](rsp.Message, "发送邮件");
                            C.refresh();
                        } else {
                            toastr["error"](rsp.Message, "发送邮件");
                        }
                    },
                    error: function () {
                        toastr["error"]("程序碰到问题没有正确执行！", "发送邮件");
                    },
                    complete: function () {
                        setComponentsEnable(true);
                        btnSend.html(btntext);
                    }
                });
            });

            // 绑定保存事件
            btnSaveDraft.bind("click", function () {
                var postData = [];
                var touid = txtSendTo.val().split(",");

                postData.push({ "name": "mid", "value": hdfMID.val() });
                postData.push({ "name": "subject", "value": txtSubject.val() });
                postData.push({ "name": "context", "value": C.Components.UEditor.getContent() });
                postData.push({ "name": "ajax", "value": true });

                for (var i in touid) {
                    if (touid[i]) postData.push({ "name": "touid", "value": touid[i] });
                }

                var btntext = btnSaveDraft.html();
                setComponentsEnable(false);
                btnSaveDraft.empty().append('<i class="fa fa-spinner fa-spin"></i> 正在保存');

                $.ajax({
                    url: "/Mail/Save",
                    type: "POST",
                    dataType: "json",
                    data: postData,
                    success: function (rsp) {
                        if (rsp.Result) {
                            toastr["success"](rsp.Message, "保存至草稿箱");
                            hdfMID.val(rsp.Data.MID);
                        } else {
                            toastr["error"](rsp.Message, "保存至草稿箱");
                        }
                    },
                    error: function () {
                        toastr["error"]("程序碰到问题没有正确执行！", "保存至草稿箱");
                    },
                    complete: function () {
                        setComponentsEnable(true);
                        btnSaveDraft.html(btntext);
                    }
                });
            });

            // 绑定删除事件
            btnDelete.bind("click", function () {
                var mid = hdfMID.val();

                if (mid) {
                    $.ajax("/Mail/MarkDelete", {
                        dataType: "json",
                        type: "POST",
                        data: function () {
                            var d = [];
                            d.push({ "name": "ajax", "value": true });
                            d.push({ "name": "mid", "value": hdfMID.val() });
                            return d;
                        } (),
                        success: function (data) {
                            if (data.Result) {
                                toastr["success"](data.Message, "删除邮件");
                                C.refresh();
                            } else {
                                toastr["error"](data.Message, "删除邮件");
                            }
                        },
                        error: function () {
                            toastr["error"]("程序碰到问题没有正确执行！", "删除邮件");
                        }
                    });
                } else {
                    C.refresh();
                }
            });
        },
        // 初始化阅读器
        initReaderBox: function () {
            var mailContent = C.Components.mailContent;

            mailContent
                .find("ul.mail-operation > li > a[data-type]:not(.mail-menu-link)")
                .bind("click", function (e) {
                    var link = $(this);
                    var type = link.data("type").toLowerCase();
                    var alertTitle = "";

                    e.preventDefault();

                    switch (type) {
                        case "markread":
                            alertTitle = "邮件已读未读标记";
                            break;
                        case "markdelete":
                            alertTitle = "删除邮件";
                            break;
                        case "restore":
                            alertTitle = "恢复邮件";
                            break;
                        case "delete":
                            alertTitle = "永久删除邮件";
                            break;
                    }

                    C.defaultAjax(this.href, [], alertTitle, function (data) {
                        if (type == "markread") {
                            C.setUnReadCount(data.UnReadCount);
                        }
                    });
                });

            mailContent
                .find(".mail-menu-link")
                .bind("click", function (e) {

                    var link = $(this);
                    var type = link.data("type").toLowerCase();
                    var alertTitle = "";

                    e.preventDefault();

                    switch (type) {
                        case "reply":
                            alertTitle = "邮件回复";
                            break;
                        case "forward":
                            alertTitle = "邮件转发";
                            break;
                    }

                    mailContent.addClass("hide");
                    mailContent.LoadingPanel.addClass("show");

                    $.ajax({
                        url: this.href || link.data("target"),
                        type: "POST",
                        data: { "ajax": true, "redirect": true },
                        dataType: "html",
                        timeout: 5000,
                        success: function (html) {
                            mailContent.empty().append(html);
                            mailContent.LoadingPanel.removeClass("show");
                            mailContent.removeClass("hide");
                            C.initEditor();
                        },
                        error: function (a, b, c) {
                            switch (b) {
                                case "timeout":
                                    mailContent.empty().append('<div class="mail-line mt-10"></div><p class="text-danger">连接服务器超时！</p>');
                                    break;
                                default:
                                    mailContent.load("/error/c500");
                                    toastr["error"]("程序碰到问题没有正确执行！", alertTitle || "程序异常");
                                    break;
                            }
                            mailContent.LoadingPanel.removeClass("show");
                            mailContent.removeClass("hide");
                        }
                    });
                });
        },
        // 初始化邮件列表
        initMailList: function (fn) {
            var mailcount = 0;
            var mailContent = C.Components.mailContent;
            var groupCheckbox = $("input.mail-group-checkbox");

            Metronic.initComponents();

            mailContent
            .find("input.mail-group-checkbox")
            .bind("click", function () {
                var set = jQuery(this).attr("data-set");
                var checked = jQuery(this).is(":checked");
                jQuery(set).each(function () {
                    $(this).attr("checked", checked);
                });
                jQuery.uniform.update(set);
            });
            // 绑定列表事件
            mailContent
            .find("table > tbody > tr[data-type]")
            .bind("click", function () {
                var link = $(this);
                var postData = C.getHashParams(link.data("target"));

                postData["mailbox"] = C.Data.MailBox;
                C.setHashParams(postData);

            })
            .children("td:has(input)")
            .bind("click", function (e) {
                e.stopPropagation();
            });

            // 绑定标记已读事件
            // 绑定标记未读事件
            // 绑定删除事件
            mailContent
                .find("ul.dropdown-menu > li > a[data-type]")
                .bind("click", function (e) {
                    var btn = $(this);
                    var alertTitle = "";
                    var mid = new PostData();
                    var type = btn.data("type").toLowerCase();
                    var chkboxes = $("#mail-list input[name='mid']:checked");

                    e.preventDefault();

                    switch (type) {
                        case "markread":
                            alertTitle = "邮件已读未读标记";
                            break;
                        case "markdelete":
                            alertTitle = "删除邮件";
                            break;
                        case "restore":
                            alertTitle = "恢复邮件";
                            break;
                        case "delete":
                            alertTitle = "永久删除邮件";
                            break;
                    }

                    chkboxes.each(function () {
                        mid.Add("mid", this.value);
                    });

                    if (mid.GetData().length == 0) {
                        toastr["warning"]("您至少需要选择一个操作对象", alertTitle || "系统消息");
                    } else {
                        C.defaultAjax(this.href, mid.GetData(), alertTitle, function () {
                            switch (type) {
                                case "markread":
                                    {
                                        var count = parseInt(C.Components.mailCountLabel.eq(0).text());
                                        var setToRead = btn.attr("href").indexOf("read=true") > -1;

                                        chkboxes.each(function () {
                                            var _chk = $(this);
                                            var _tr = _chk.closest("tr");

                                            if (setToRead) {
                                                if (_tr.hasClass("unread")) {
                                                    _tr.removeClass("unread");
                                                    count--;
                                                }
                                            } else {
                                                if (!_tr.hasClass("unread")) {
                                                    _tr.addClass("unread");
                                                    count++;
                                                }
                                            }

                                            _chk.trigger("click");
                                        });

                                        C.setUnReadCount(count);

                                        if (groupCheckbox.is(":checked")) {
                                            groupCheckbox.trigger("click");
                                        }
                                        break;
                                    }
                                default:
                                    {
                                        C.refresh();
                                        break;
                                    }
                            }
                        });
                    }
                });

            return {
                MailCount: function () {
                    return mailcount;
                }
            }
        },
        // 初始化新建邮件
        initNewBox: function () {
            this.triggerLink(this.Components.btnNewBox);
            this.initMailList();
        },
        // 初始化收件箱
        initInbox: function () {
            this.triggerLink(this.Components.btnInbox);
            this.initMailList();
        },
        // 初始化发件箱
        initSendBox: function () {
            this.triggerLink(this.Components.btnSendBox);
            this.initMailList();
        },
        // 初始化草稿箱
        initDraftBox: function () {
            this.triggerLink(this.Components.btnDraftBox);
            this.initMailList();
        },
        // 初始化垃圾箱
        initTrashBox: function () {
            this.triggerLink(this.Components.btnTrashBox);
            this.initMailList();
        },
        // 设置未读邮件标记
        setUnReadCount: function (count) {
            C.Components.mailCountLabel.each(function () {
                var label = $(this);

                label.html(count);

                if (label.hasClass("badge-mail")) {
                    if (count == 0) {
                        label.addClass("hide");
                    } else {
                        label.removeClass("hide");
                    }
                }
            });
        },
        defaultAjax: function (postUrl, postData, alertTitle, fn) {
            if (postData instanceof Array) {
                postData.push({ "name": "ajax", "value": true });
                postData.push({ "name": "redirect", "value": true });
            } else {
                postData["ajax"] = true;
                postData["redirect"] = true;
            }

            $.ajax({
                url: postUrl,
                type: "POST",
                data: postData,
                timeout: 5000,
                success: function (rsp) {
                    if (rsp.Result) {
                        toastr["success"](rsp.Message, alertTitle || "系统消息");
                        if (fn) {
                            fn.call(this, rsp.Data);
                        }
                    } else {
                        toastr["error"](rsp.Message, alertTitle || "系统消息");
                    }
                },
                error: function (a, b, c) {
                    switch (b) {
                        case "timeout":
                            toastr["warning"]("连接服务器超时！", "服务器未响应");
                            break;
                        default:
                            toastr["error"]("程序碰到问题没有正确执行！", "程序异常");
                            break;
                    }
                },
                complete: function () {
                }
            });
        },
        initHashChange: function () {
            hashchange();

            window.onhashchange = hashchange;
            function hashchange() {
                var params = C.getHashParams(location.hash);
                var type = params["mailbox"] || "inbox";
                var action = params["action"] || '/Mail/';
                var callfn = null;
                var postData = new PostData();
                var target = action.match(/[^\/]+/g);

                target = target ? target.pop() : "";
                switch (target.toLowerCase()) {
                    case "editor":
                        callfn = C.initEditor;
                        break;
                    case "reader":
                        callfn = C.initReaderBox;
                        break;
                }

                for (var key in params) {
                    if (params[key] instanceof Array) {
                        for (var i in params[key]) {
                            postData.Add(key, params[key][i]);
                        }
                    } else {
                        postData.Add(key, params[key]);
                    }
                }

                postData.Add("ajax", true);
                postData.Add("redirect", true);
                C.Data.MailBox = type;

                var mailContent = C.Components.mailContent;
                mailContent.addClass("hide");
                mailContent.LoadingPanel.addClass("show");

                $.ajax({
                    url: action,
                    type: "POST",
                    data: postData.GetData(),
                    dataType: "html",
                    timeout: 5000,
                    success: function (html) {
                        mailContent.empty().append(html);
                        // 必须在调用编辑器之前显示目标，否则编辑器显示不了宽
                        mailContent.LoadingPanel.removeClass("show");
                        mailContent.removeClass("hide");

                        switch (type) {
                            case "new":
                                C.initNewBox();
                                break;
                            case "draft":
                                C.initDraftBox();
                                break;
                            case "inbox":
                                C.initInbox();
                                break;
                            case "send":
                                C.initSendBox();
                                break;
                            case "trash":
                                C.initTrashBox();
                                break;
                        }

                        if (callfn) {
                            callfn.call(this);
                        }

                        Metronic.initComponents();
                    },
                    error: function (a, b, c) {
                        switch (b) {
                            case "timeout":
                                mailContent.empty().append('<div class="mail-line mt-10"></div><p class="text-danger">连接服务器超时！</p>');
                                break;
                            default:
                                mailContent.load("/error/c500");
                                toastr["error"]("程序碰到问题没有正确执行！", "程序异常");
                                break;
                        }
                        mailContent.LoadingPanel.removeClass("show");
                        mailContent.removeClass("hide");
                    }
                });
            }
        },
        triggerLink: function (link) {
            var mailContent = C.Components.mailContent;

            if (C.Components.currentButton) {
                C.Components
                            .currentButton
                            .parent()
                            .removeClass("active");
            }

            link.parent().addClass("active");
            C.Components.currentButton = link;
            mailContent.Title.html(link.data("title"));
        },
        // 设置哈希值
        setHashParams: function (params) {
            var p = [];

            if (params instanceof Array) {
                for (var i in params) {
                    p.push(params[i]["name"] + "=" + params[i]["value"]);
                }
            } else {
                for (var key in params) {
                    if (params[key] instanceof Array) {
                        for (var i in params[key]) {
                            p.push(key + "=" + params[key][i]);
                        }
                    } else {
                        p.push(key + "=" + params[key]);
                    }
                }
            }

            location.hash = Base64.encode(p.join("&"));
        },
        // 获取哈希参数
        getHashParams: function (url) {
            var match = url.match(/#[^#]+/);
            var hash = match ? match[0].substr(1) : null;
            var params = {};

            if (!hash) return params;

            hash = Base64.decode(hash);

            var hashArray = hash.split("&");

            for (var i in hashArray) {
                var idx = hashArray[i].indexOf("=");
                var key = null;
                var value = null;

                if (idx == -1) {
                    key = hashArray[i];
                } else {
                    key = hashArray[i].substr(0, idx);
                    value = hashArray[i].substr(idx + 1);
                }

                if (params[key] === undefined) {
                    params[key] = value;
                } else {
                    if (!(params[key] instanceof Array)) {
                        params[key] = [params[key]];
                    }

                    params[key].push(value);
                }
            }

            return params;
        },
        refresh: function () {
            var hash = location.hash;

            if (!hash) return;

            var params = C.getHashParams(hash);

            params["timestamp"] = (new Date()).getTime();

            C.setHashParams(params);
        }
    };

    C.init();

    return {
        Data: C.Data,
        SetMailToRead: function () {
            C.setUnReadCount(parseInt(C.Components.mailCountLabel.eq(0).text()) - 1);
        }
    }
} ();